package com.netty.demo.nio.handler.impl;

import com.netty.demo.protocol.packet.LoginRequestPacket;
import com.netty.demo.protocol.packet.LoginResponsePacket;
import com.netty.demo.utils.LoginUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) throws Exception{
        // 登录流程
        System.out.println(new Date() + ": 客户端（" + loginRequestPacket.getUserId() + "）开始登录……");

        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());
        if (!LoginUtils.valid(loginRequestPacket)) {
            loginResponsePacket.setReason("账号密码校验失败");
            loginResponsePacket.setSuccess(false);
            System.out.println(new Date() + ": 登录失败!");
        } else {
            loginResponsePacket.setSuccess(true);
            loginResponsePacket.setUserId(loginRequestPacket.getUserId());
            System.out.println(new Date() + ": 登录成功!");
        }
        LoginUtils.recordLogin(ctx.channel(), loginRequestPacket.getUserId());
        // 登录响应
        ctx.channel().writeAndFlush(loginResponsePacket);
    }
}
